package com.nineclock.sign.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.filter.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.common.utils.DateTimeUtil;
import com.nineclock.sign.dto.SignUserDTO;
import com.nineclock.sign.mapper.SignInfoMapper;
import com.nineclock.sign.mapper.SignPictureMapper;
import com.nineclock.sign.pojo.SignInfo;
import com.nineclock.sign.pojo.SignPicture;
import com.nineclock.sign.service.SignService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class SignServiceImpl implements SignService {
    @Autowired
    private SignInfoMapper signInfoMapper;

    @Autowired
    private SignPictureMapper pictureMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void sign(SignUserDTO signUserDTO){
        //1.参数校验
        if (signUserDTO == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //2 封装签到信息
        SignInfo signInfo = BeanHelper.copyProperties(signUserDTO, SignInfo.class);
        //2.1 设置签到基本信息：员工id，公司id，创建时间
        signInfo.setCompanyUserId(CurrentUserHolder.get().getCompanyUserId());
        signInfo.setCompanyId(CurrentUserHolder.get().getCompanyId());
        signInfo.setCreateTime(new Date());

        // 2.2 设置签到日期和月份（以服务端为准，否则用户可以在客户端修改手机时间打卡）
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = simpleDateFormat.format(new Date());
        signInfo.setCreateDate(dateString);
        //设置签到年月份，使用Calendar类（月份是0-11）
        Calendar instance = Calendar.getInstance();
        int y = instance.get(Calendar.YEAR);
        int m = instance.get(Calendar.MONTH) + 1;
        String year = String.valueOf(y);
        String month = String.valueOf(m);
        //拼接年份+月份字符串
        String createMonth = year + "-" + month;
        signInfo.setCreateMonth(createMonth);

        //2.3 设置签到经度、纬度和地址
        signInfo.setLat(signUserDTO.getLat());
        signInfo.setLng(signUserDTO.getLng());
        signInfo.setAddress(signUserDTO.getAddress());

        //2.4 设置签到备注、拜访对象和手机标识
        signInfo.setRemark(signUserDTO.getRemark());
        signInfo.setVisit(signUserDTO.getVisit());
        signInfo.setImei(signUserDTO.getImei());

        //2.5保存签到信息到sign_info表

        signInfoMapper.insert(signInfo);

        //2.6 把签到的图片阿里云地址保存到签到图片表中
        //2.6.1 设置sign_picture表的签到id
        SignPicture signPicture = new SignPicture();
        signPicture.setSignId(signInfo.getId());

        String[] imageList = signUserDTO.getImages().split(",");
        for (String image : imageList) {
            signPicture.setUrl(image);
            pictureMapper.insert(signPicture);
        }

        // 3.更新用户当天签到次数和当月签到次数到redis

        // 更新用户当天签到次数到redis
        Integer dayCount;
        //设置redis当日签到次数的key
        String dayCountKey = CurrentUserHolder.get().getCompanyId() + "," + CurrentUserHolder.get().getCompanyUserId() + "," + signInfo.getCreateDate();
        if (StringUtils.isEmpty(redisTemplate.opsForValue().get(dayCountKey))) {
            dayCount = 0;
        } else {
            String dayCountStr = (String) redisTemplate.opsForValue().get(dayCountKey);
            dayCount = Integer.parseInt(dayCountStr);
        }
        //每签到一次，redis当日签到次数+1
        dayCount++;
        //把int类型dayCount转为String类型
        String redisDayCountStr = String.valueOf(dayCount);
        //更新redis当日签到次数
        redisTemplate.opsForValue().set(dayCountKey, redisDayCountStr);


        //更新用户当月签到次数到redis
        Integer monthCount;
        //设置redis当月签到次数的key
        String monthCountKey = CurrentUserHolder.get().getCompanyId() + "," + CurrentUserHolder.get().getCompanyUserId() + "," + signInfo.getCreateMonth();
        if (StringUtils.isEmpty(redisTemplate.opsForValue().get(monthCountKey))) {
            monthCount = 0;
        } else {
            String monthCountStr = (String) redisTemplate.opsForValue().get(monthCountKey);
            monthCount = Integer.valueOf(monthCountStr);
        }
        //每签到一次，redis当月签到次数+1
        monthCount++;
        //把int类型dayCount转为String类型
        String redismonthCountStr = String.valueOf(monthCount);

        redisTemplate.opsForValue().set(monthCountKey, redismonthCountStr);

    }

    /**
     * 接口名称：APP: 获取当前用户当天签到次数
     * 未完成更新时间：2021-12-10 20:32:19
     */
    @Override
    public Integer getDayCount() {
        Date date = new Date();
        String dateToStr = DateTimeUtil.dateToStr(date, DateTimeUtil.TIME_FORMAT_2);
        String dayCountKey = CurrentUserHolder.get().getCompanyId() + "," + CurrentUserHolder.get().getCompanyUserId() + "," + dateToStr;
        String value = ((String) redisTemplate.opsForValue().get(dayCountKey));
        if (value==null){
            throw new NcException(ResponseEnum.SERVER_ERROR);
        }
        int count = Integer.parseInt(value);
        return count;
    }
}
